package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"net/http"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service/dto"
	cDto "tuowei.com/common/dto"
)

type SysVersion struct {
	api.Api
}

func (v SysVersion) Insert(ctx *gin.Context) {
	req := dto.SysVersionInsertReq{}
	err := v.MakeContext(ctx).MakeOrm().Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		v.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	obj := new(models.SysVersion)
	req.Generate(obj)
	err = v.Orm.Create(obj).Error
	if err != nil {
		v.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	v.OK(obj, "success")
}

//Update

func (v SysVersion) Update(ctx *gin.Context) {
	req := dto.SysVersionInsertReq{}
	err := v.MakeContext(ctx).MakeOrm().Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		v.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	obj := new(models.SysVersion)
	req.Generate(obj)
	err = v.Orm.Updates(obj).Error
	if err != nil {
		v.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	v.OK(obj, "success")
}

func (v SysVersion) Delete(ctx *gin.Context) {
	err := v.MakeContext(ctx).MakeOrm().Errors
	if err != nil {
		v.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	err = v.Orm.Where("id = ?", ctx.Param("id")).Delete(models.SysVersion{}).Error
	if err != nil {
		if err != nil {
			v.Error(http.StatusInternalServerError, err, err.Error())
			return
		}
	}
	v.OK(nil, "删除成功")
}

func (v SysVersion) List(ctx *gin.Context) {
	req := dto.SysVersionListReq{}
	err := v.MakeContext(ctx).MakeOrm().Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		v.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	lists := make([]models.SysVersion, 0)
	var count int64
	err = v.Orm.Scopes(cDto.Paginate(req.GetPageSize(), req.GetPageIndex())).Find(&lists).Limit(-1).Offset(-1).Count(&count).Error
	if err != nil {
		v.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	v.PageOK(lists, int(count), req.GetPageIndex(), req.GetPageSize(), "success")
}
